package org.bloodnoteii.cloudprovider.dataBase;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Driver;

@Configuration
@MapperScan(basePackages = "org.bloodnoteii.cloudprovider.hello.mapper.neo4j",sqlSessionFactoryRef = "neo4jSqlSessionFactory")
public class Neo4jConfig {
    @Value("${spring.datasource.neo4j.driver-class-name}")
    String driverClass;
    @Value("${spring.datasource.neo4j.url}")
    String url;
    @Value("${spring.datasource.neo4j.username}")
    String userName;
    @Value("${spring.datasource.neo4j.password}")
    String passWord;
    @Bean(name = "neo4jDataSource")
    @ConfigurationProperties("spring.datasource.neo4j")
    public DataSource neo4jDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }
    @Bean(name = "neo4jSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("neo4jDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/neo4j/*.xml"));

        //**配置多数据源需要设置驼峰规则，否则不生效**
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactoryBean.setConfiguration(configuration);

        return sessionFactoryBean.getObject();
    }
    @Bean(name = "neo4jSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionFactoryTemplate(@Qualifier("neo4jSqlSessionFactory")SqlSessionFactory sqlSessionFactory ) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
